package com.exce.config;

/**
 * @author yinxing
 * @date 2022-09-09
 */

import com.exce.entity.ExceptionEntity;
import com.exce.enums.ErrorEnum;
import com.exce.service.ExceptionService;
import com.exce.vo.Response;
import com.exce.vo.DiyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.annotation.Resource;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
@Component
public class GlobalExceptionHandler {

    @Resource
    private ExceptionService exceptionService;

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(value = DiyException.class)
    public Response bizExceptionHandler(DiyException e) {
        log.error(e.getMessage(), e);
        exceptionService.addException(ExceptionEntity.builder()
                .exceptionMessage(e.getMessage())
                .exceptionType(ErrorEnum.SELF_EXCEPTION.getErrorMsg())
                .build());
        return Response.defineError(e);
    }

    /**
     * 处理Exception异常
     */
    @ExceptionHandler(value = Exception.class)
    public Response exceptionHandler(Exception e) {
        StringBuffer stringBuffer = new StringBuffer("错误信息: [" + e.getMessage());
        int number = 0;
        for (StackTraceElement element : e.getStackTrace()) {
            if (element.getClassName().contains(ErrorEnum.CONTROLLER.getErrorMsg())
                    || element.getClassName().contains(ErrorEnum.SERVICE.getErrorMsg())
                    || element.getClassName().contains(ErrorEnum.MAPPER.getErrorMsg())) {
                stringBuffer.append("] 序号:[" + ++number + "] " +
                        "文件:[" + element.getFileName() + "] " +
                        "方法:[" + element.getMethodName() + "] " +
                        "代码行:[" + element.getLineNumber() + "] ");
            }
        }
        exceptionService.addException(ExceptionEntity.builder()
                .exceptionMessage(stringBuffer.toString())
                .exceptionType(ErrorEnum.SYSTEM_EXCEPTION.getErrorMsg())
                .build());
        log.info("异常信息:{}", stringBuffer.toString());
        return Response.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);

    }

}
